<template>
  <div class="vsCode">
    <div class="hander">

    </div>
    <div class="treeAndCode">
      <el-tree v-if="data.length > 0" node-key="id" :default-expanded-keys="[1]" :data="data" draggable="true"
        @node-click="handleNodeClick" />
      <div class="tree" v-else>
        <button @click="DirectoryPicker">导入项目</button>
      </div>
      <div class="code">
        <!-- bind to a data property named `code` -->
        <highlightjs class="hljs-main scrollbar" :code="highlightedCode" />
        <!-- or literal code works as well -->
        <textarea @scroll="textareaScroll" ref="textarea" @input="textareaInput" v-model="highlightedCode"
          spellcheck="false" class="textarea-main" name="" id="" cols="30"></textarea>
        <div class="lineNumber">
          <p v-for="item in lineList">{{ item }}</p>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { getpicker } from "@/utils";
import { ref, watch } from "vue"
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import xml from 'highlight.js/lib/languages/xml';
import css from 'highlight.js/lib/languages/css';
import json from 'highlight.js/lib/languages/json';
import markdown from 'highlight.js/lib/languages/markdown';

import { type Handle } from "@/types";
hljs.registerLanguage('xml', xml);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('css', css);
hljs.registerLanguage('json', json);
hljs.registerLanguage('markdown', markdown);
const lineList = ref<number[]>([1])
const textarea = ref<HTMLTextAreaElement>()
const data = ref<Handle[]>([])
const highlightedCode = ref<string>(`暂无代码!!!`)
const handleNodeClick = async (data: any) => {
  if (data.kind === "file") {
    const file = await data.getFile()
    const readFile = new FileReader()
    readFile.readAsText(file)
    readFile.onload = (e) => {
      highlightedCode.value = e.target?.result as string
    }
    (textarea.value!).scrollTo(0, 0);
    textareaScroll()
  }
}

const 排序 = (item: Handle) => {
  if (item.kind === "file") {
    return
  }
  item.children?.sort((a: Handle, b: Handle) => {
    if (a.kind[0].toLowerCase().charCodeAt(0) < b.kind[0].toLowerCase().charCodeAt(0)) {
      return -1
    } else if (a.kind[0].toLowerCase().charCodeAt(0) > b.kind[0].toLowerCase().charCodeAt(0)) {
      return 1
    }
    if (a.name[0].toLowerCase().charCodeAt(0) < b.name[0].toLowerCase().charCodeAt(0)) {
      return -1

    } else if (a.name[0].toLowerCase().charCodeAt(0) > b.name[0].toLowerCase().charCodeAt(0)) {
      return 1

    }
    return 0
  })
  // item.children?.sort((a: Handle, b: Handle) => {
  //   return a.name[0].toLowerCase().charCodeAt(0) - b.name[0].toLowerCase().charCodeAt(0)
  // })
  item.children?.forEach(item => {
    排序(item)
  })
}
const DirectoryPicker = async () => {
  try {
    const handle: Handle = await (window as any).showDirectoryPicker();
    console.log(handle, "句柄");
    handle.id = 1
    const handles = await getpicker(handle)
    排序(handles)
    console.log(handles, "排序");
    data.value.push(handles)


  } catch (e) {
    alert("用户拒绝授权!!")
  }
}
//监听滚动条事件 控制高亮代码一起滚动
const textareaScroll = () => {
  const hljsCode = document.querySelector('.hljs')
  const lineNumber = document.querySelector('.lineNumber')
  if (lineNumber && hljsCode && textarea.value && textarea.value.scrollTop > 0) {
    hljsCode.scrollTo(0, textarea.value.scrollTop)
    lineNumber.scrollTo(0, textarea.value.scrollTop)
  }

}
//利用input增加行号
// 监听 count 的变化
watch(highlightedCode, (newValue, oldValue) => {
  console.log("执行了");
  setTimeout(() => {
    const hljsCode: any = document.querySelector('.hljs')
    const hljsCodeTop = hljsCode?.childNodes[hljsCode?.childNodes.length - 1]
    let line = 1
    const lineHeight = +getComputedStyle(textarea.value as Element).lineHeight.split("px")[0]
    console.log(hljsCode?.childNodes.length, "index");

    if (lineHeight >= (textarea.value!).scrollHeight) {
      line = (textarea.value!).scrollHeight / lineHeight
      console.log(line);

    } else {
      if (hljsCode?.childNodes.length <= 1) {
        if (hljsCodeTop?.previousSibling) return
        line = 1
      }
      if (hljsCodeTop?.nodeName == "#text") {

        line = (hljsCodeTop?.previousSibling?.offsetTop || 0) / lineHeight + hljsCodeTop.textContent.split("\n").length
        console.log(hljsCode?.childNodes);
      } else {
        line = (hljsCodeTop?.offsetTop || 0) / lineHeight + 1
        console.log("span", line);

      }


    }
    const lines = []
    for (let i = 1; i <= +line; i++) {
      lines.push(i)
    }
    lineList.value = lines
  }, 0)

})

const textareaInput = (e: any) => {

}
</script>

<style lang="scss" scoped>
.vsCode {
  height: 100vh;
  width: 100vw;
  background-color: rgba(0, 0, 0, 0.2);
  padding-top: 100px;

  .treeAndCode {
    display: flex;
    height: 100%;
    background-color: rgba(68, 68, 68, 0.5);

    .tree {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      background-color: rgba(31, 31, 31, 0.8);
      width: 350px;

      button {
        background-color: rgb(0, 142, 251);
        color: aliceblue;
        border: 1px solid rgba(37, 171, 255, 0.8);
        border-radius: 2px;
        width: 170px;
        height: 30px;

        &:hover {
          background-color: rgb(30, 157, 255);

        }

        &:focus {
          border: 1px solid rgb(255, 255, 255);

        }
      }
    }

    .code {
      position: relative;
      width: 100%;
      height: 100%;
      background-color: rgba(31, 31, 31, 0.7);

      .lineNumber {
        position: absolute;
        // top: 2.2%;
        // left: 25px;
        padding: 16px 17px 17px 10px;
        height: 100%;
        overflow-y: auto;
        width: 45px;
        z-index: 0;

        p {
          font-size: 15px;
        }

        /* 滚动条 */
        &::-webkit-scrollbar {
          width: 0px !important;
          height: 0px !important;
        }
      }
    }
  }
}

.el-tree {
  @extend .scrollbar;
  width: 350px;
  height: 100%;
  background-color: rgba(31, 31, 31, 0.8);
  color: aliceblue;
  overflow-y: auto;


}

:deep(.el-tree-node__content:hover, .el-tree-node__content:hover) {
  background-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-tree-node:focus>.el-tree-node__content) {
  background-color: rgba(0, 120, 194, 0.5);
  border: 1px solid rgba(37, 171, 255, 0.8);
}

//代码高亮
.hljs-main,
.textarea-main {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;

}

.textarea-main {
  @extend .scrollbar;
  color: rgb(3, 107, 197, 0);
  caret-color: rgb(255, 255, 255);
  background-color: rgba(240, 248, 255, 0);
  font-size: 15px;
  padding: 14px 17px 17px 49px;
  line-height: 24px;
  height: 100%;
  width: 100%;
  resize: none;
  border: none;

  &::selection {
    background-color: rgba(0, 157, 255, 0.2);
  }

  &:focus {
    border: 0;
    outline: none;
  }


}

:deep(.hljs) {
  @extend .scrollbar;
  height: 100%;
  width: 100%;
  border: 0;
  overflow-x: none;
  overflow-y: auto;
  white-space: pre-wrap;
  padding-left: 50px;
  background-color: rgba(22, 22, 22, 0.8) !important;
  color: #acdbfc;


  //方法名
  .function_ {
    color: burlywood;
  }

  //属性名
  .hljs-attr {
    color: #0294fc;
  }

  //按需导入
  .class_ {
    color: #44a5ea;

  }

  //函数参数
  .hljs-params {
    color: #d588fb;

  }
}

//滚动条样式
.scrollbar {
  &:hover {

    /* 滚动条滑块 */
    &::-webkit-scrollbar-thumb {
      border-radius: 1px;
      background: rgba(106, 106, 106, 0.3) !important;
    }

    /* 滚动条轨道 */
    &::-webkit-scrollbar-track {
      background-color: rgba(16, 16, 16, 0.112);
    }
  }

  /* 滚动条轨道 */
  &::-webkit-scrollbar-track {
    background: rgba(0, 166, 255, 0);
  }

  /* 滚动条滑块 */
  &::-webkit-scrollbar-thumb {
    border-radius: 1px;
    background: rgba(106, 106, 106, 0) !important;
  }

  /* 滚动条滑块悬停状态 */
  &::-webkit-scrollbar-thumb:hover {
    background: rgba(171, 171, 171, 0.3) !important;


  }

  /* 滚动条 */
  &::-webkit-scrollbar {
    width: 8px;
    height: 0px;
  }
}
</style>